﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;

namespace USERS.CYT369.COM.DAL
{
    public class DocumentService : USERS.CYT369.COM.DAL.DbContexts.NewsBaseService<DocumentService>
    {
        public DocumentService() { }

        #region Article
        /// <summary>
        /// 保存文章信息
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public bool SaveDocument(USERS.CYT369.COM.MODELS.Articles.Document document)
        {
            document.ChangedTime = DateTime.Now;
            using (var ctx = this.NewsCtx)
            {
                var item = ctx.Documents.Where(c => c.Id == document.Id && c.EditorUserID == document.EditorUserID).Include(c => c.DocExt).FirstOrDefault();
                if (item == null)
                {
                    document.CreatedTime = DateTime.Now;
                    document.ChangedTime = document.CreatedTime;
                    document.Year = document.CreatedTime.Year;
                    document.Month = document.CreatedTime.Month;
                    document.Day = document.CreatedTime.Day;
                    ctx.Documents.Add(document);
                }
                else
                {
                    item.ContentType = document.ContentType;
                    item.ContentSourceID = document.ContentSourceID;
                    item.DocumentTypeID = document.DocumentTypeID;

                    item.PreviewImg = document.PreviewImg;
                    item.Title = document.Title;
                    item.Summary = document.Summary;
                    item.Author = document.Author;
                    item.CanComment = document.CanComment;
                    item.IsAds = document.IsAds;
                    item.GotoTarget = document.GotoTarget;
                    item.TargetURL = document.TargetURL;

                    item.EditorUserID = document.EditorUserID;
                    item.EditorName = document.EditorName;
                    item.EditorFullName = document.EditorFullName;

                    item.Published = false;
                    item.AuditStatusID = document.AuditStatusID;

                    item.DocExt.SubHead = document.DocExt.SubHead;
                    item.DocExt.DocContent = document.DocExt.DocContent;

                    item.ChangedTime = DateTime.Now;
                }

                ctx.SaveChanges();

                return true;
            }
        }

        /// <summary>
        /// 更新预览图片
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="imgKey"></param>
        /// <param name="oldImgKey"></param>
        /// <returns></returns>
        public bool UpdateDocumentPreviewImg(long docId, string imgKey, ref string oldImgKey)
        {
            using (var ctx = this.NewsCtx)
            {
                var item = ctx.Documents.Where(c => c.Id == docId).FirstOrDefault();
                if (item != null)
                {
                    oldImgKey = item.PreviewImg;
                    item.PreviewImg = imgKey;
                    ctx.SaveChanges();
                    
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 保存附件
        /// </summary>
        /// <param name="attachment"></param>
        /// <returns></returns>
        public bool SaveDocAttachment(USERS.CYT369.COM.MODELS.Articles.DocAttachment attachment)
        {
            attachment.ChangedTime = DateTime.Now;
            using (var ctx = this.NewsCtx)
            {
                var document = ctx.Documents.Where(c => c.Id == attachment.DocID).FirstOrDefault();
                if (document != null)
                {
                    document.AuditStatusID = 0;
                    document.Published = false;
                    var item = ctx.DocAttachments.Where(c => c.Id == attachment.Id).FirstOrDefault();
                    if (item == null)
                    {
                        ctx.DocAttachments.Add(attachment);
                    }
                    else
                    {
                        item.Sequence = attachment.Sequence;
                        item.FileExtension = attachment.FileExtension;
                        item.ImagePath = attachment.ImagePath;

                        item.ChangedTime = DateTime.Now;
                    }

                    ctx.SaveChanges();
                }
                return true;
            }
        }

        /// <summary>
        /// 删除文章资源
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool DeleteArticleAttachment(long docId, long fileId, long userId)
        {
            using (var ctx = this.NewsCtx)
            {
                var document = (from o in ctx.Documents.Include(c => c.Attachments)
                                where o.Id == docId && o.EditorUserID == userId
                                select o).FirstOrDefault();

                {
                    var attachment = (from o in document.Attachments
                                      where o.Id == fileId
                                      select o).FirstOrDefault();

                    if (attachment != null)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(attachment.ImagePath))
                            {
                                USERS.CYT369.COM.UTILITY.OssClientService.Instance.RemoveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, attachment.ImagePath);
                            }
                        }
                        catch { }

                        ctx.DocAttachments.Remove(attachment);
                        ctx.SaveChanges();

                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 查询文章信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public USERS.CYT369.COM.MODELS.Articles.Document GetDocumentByID(long id, long userId)
        {
            return base.GetOne<USERS.CYT369.COM.MODELS.Articles.Document, USERS.CYT369.COM.MODELS.Articles.DocumentExt>(c => c.DocExt, c => c.Id == id && c.EditorUserID == userId);
        }

        /// <summary>
        /// 查询文章信息（包含图片）
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public USERS.CYT369.COM.MODELS.Articles.Document GetDocumentByID_IncludeImg(long docId, long userId)
        {
            using (var ctx = this.NewsCtx)
            {
                var document = (from o in ctx.Documents.Include(c => c.DocExt).Include(c => c.Attachments)
                                where o.Id == docId && o.EditorUserID == userId
                                select o).FirstOrDefault();

                return document;
            }
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool DeleteArticle(long docId, long userId)
        {
            using (var ctx = this.NewsCtx)
            {
                var document = (from o in ctx.Documents.Include(c => c.DocExt).Include(c => c.Attachments)
                                where o.Id == docId && o.EditorUserID == userId
                                select o).FirstOrDefault();

                if (document != null)
                {
                    if (document.Read > 0)
                    {
                        document.Published = false;
                        document.Deleted = true;
                        ctx.SaveChanges();
                    }
                    else
                    {
                        #region 移除OSS上的文件
                        if (document.Attachments != null)
                        {
                            foreach (var files in document.Attachments)
                            {
                                try
                                {
                                    if (!string.IsNullOrEmpty(files.ImagePath))
                                    {
                                        USERS.CYT369.COM.UTILITY.OssClientService.Instance.RemoveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, files.ImagePath);
                                    }
                                }
                                catch { }
                            }
                        }
                        #endregion

                        ctx.Documents.Remove(document);
                        ctx.SaveChanges();
                    }

                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool SubmitAudit(long docId, long userId)
        {
            using (var ctx = this.NewsCtx)
            {
                var item = (from o in ctx.Documents.Include(c => c.DocExt)
                            where o.Id == docId && o.EditorUserID == userId
                            select o).FirstOrDefault();

                if (item != null)
                {
                    if (string.IsNullOrEmpty(item.Title) || item.Title == "[未命名]") { return false; }
                    if (item.DocExt == null) { return false; }
                    if (string.IsNullOrEmpty(item.DocExt.DocContent)) { return false; }

                    item.AuditStatusID = 10;
                }

                ctx.SaveChanges();

                return true;
            }
        }

        /// <summary>
        /// 获取所有的文章
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="total"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public IQueryable<USERS.CYT369.COM.MODELS.Articles.Document> GetDocuments(int page, int rows, ref int total, long userId,
                                                                                 int? status = null, string title = null,
                                                                                 int? year = null, int? month = null,
                                                                                 int? docTypeId = null)
        {
            var items = base.Get<USERS.CYT369.COM.MODELS.Articles.Document>(c => c.EditorUserID == userId);
            if (status.HasValue)
            {
                items = items.Where(c => c.AuditStatusID == status.Value);
            }

            if (year.HasValue)
            {
                items = items.Where(c => c.Year == year.Value);
            }

            if (month.HasValue)
            {
                items = items.Where(c => c.Month == month.Value);
            }

            if (docTypeId.HasValue)
            {
                items = items.Where(c => c.ContentType == docTypeId.Value || c.DocumentTypeID == docTypeId.Value);
            }

            if (!string.IsNullOrEmpty(title))
            {
                items = items.Where(c => c.Title.Contains(title));
            }

            return items = this.Pagination(page, rows, ref total, items, c => c.Id);
        }


        public USERS.CYT369.COM.MODELS.Articles.DocumentStastics GetDocumentStastics(long userId)
        {
            var items = base.Get<USERS.CYT369.COM.MODELS.Articles.Document>(c => c.EditorUserID == userId);

            var stastics = new USERS.CYT369.COM.MODELS.Articles.DocumentStastics()
            {
                TotalDoc = items.Where(c => c.Deleted == false).Count(),
                PassedAudit = items.Where(c => c.Deleted == false && c.AuditStatusID == 1).Count(),
                FailedAudit = items.Where(c => c.Deleted == false && c.AuditStatusID == 2).Count(),
                Draft = items.Where(c => c.Deleted == false && c.AuditStatusID == 0).Count(),
                YearGroup = (from o in items
                             group o by o.Year into go
                             select go.Key).ToArray(),

                MonthGroup = (from o in items
                              group o by o.Month into go
                              select go.Key).ToArray()
            };

            return stastics;
        }
        #endregion

        #region UserDocCategory
        /// <summary>
        /// 获取栏目树
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="not_id"></param>
        /// <returns></returns>
        public IEnumerable<USERS.CYT369.COM.MODELS.Articles.UserDocCategory> GetUserDocCategorys(long userId, long parentId = 0, int? not_id = null, DbContext db = null)
        {
            if (db == null)
            {
                db = this.Ctx;
            }
            IQueryable<USERS.CYT369.COM.MODELS.Articles.UserDocCategory> menus = null;
            if (not_id.HasValue)
            {
                menus = from o in db.Set<USERS.CYT369.COM.MODELS.Articles.UserDocCategory>()
                        where o.UserID == userId && o.ParentID == parentId && o.Id != not_id.Value
                        select o;
            }
            else
            {
                menus = from o in db.Set<USERS.CYT369.COM.MODELS.Articles.UserDocCategory>()
                        where o.UserID == userId && o.ParentID == parentId
                        select o;
            }

            foreach (var m in menus)
            {
                foreach (var sm in GetUserDocCategorys(userId, m.Id, not_id, db))
                {
                    m.SubTypes.Add(sm);
                }
            }

            return menus.OrderBy(c => c.Sequence);
        }


        #endregion

    }
}
